%%%----------------------------------------------------------------------
%%% File    : database.erl
%%% Author  : 
%%% Purpose : handle database
%%% Created : 14 Apr 2011
%%% Id      :
%%%----------------------------------------------------------------------

-module(database).

%% Include record files
-include_lib("stdlib/include/qlc.hrl").
-include("record.hrl").

%% External exports
-export([create_database/0,
		 start/0,
		 stop/0,
		 insert/1,
		 delete/2,
		 select/1]).

%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------

%%This function do need to be executed only once 
create_database() ->
	mnesia:create_schema([node()]),
	mnesia:start(),
	mnesia:create_table(nc_resource, [{type, bag}, {attributes, record_info(fields, nc_resource)}]),
	mnesia:stop().

start() ->
	mnesia:start(),
	mnesia:wait_for_tables([nc_resource],20000).

stop() ->
	mnesia:stop().

select(Name) ->
	if
		Name=:=nc_resource ->
			find(qlc:q([X||X <- mnesia:table(nc_resource)]))
	end.

find(Q) ->
	F=fun() -> qlc:e(Q) end,
	{atomic,Val}=mnesia:transaction(F),
	Val.

insert(NC_RESOURCE) ->
%	NC_RESOURCE = #nc_resource{memory_all=A, memory_dom0=B, data_disk=C, nc_ip=D, nc_name=E},
	F=fun() ->
		mnesia:write(NC_RESOURCE)
	end,
	mnesia:transaction(F).

delete(Table, Key) ->
		D={Table, Key},
		F=fun() ->
			mnesia:delete(D)			  
		  end,
		mnesia:transaction(F).
